﻿using AutoMapper;
using InitQ.Cache;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using SkiaSharp;
using Smart.Admin.Domain.Common;
using Smart.Admin.Domain.Model.Config;
using Smart.Admin.Domain.Model.Const;
using Smart.Admin.Domain.Model.Entity;
using Smart.Admin.Domain.Model.Enum;
using Smart.Admin.Domain.Model.Request.Account;
using Smart.Admin.Domain.Model.Request.HelpDoc;
using Smart.Admin.Domain.Model.Response;
using Smart.Admin.Domain.Model.Response.Account;
using Smart.Admin.Domain.Model.Response.HelpDoc;
using Smart.Admin.Domain.Model.Response.Menu;
using Smart.Admin.Domain.Repository;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Smart.Admin.Domain.Model.Request.Employee;
using Smart.Admin.Domain.Model.Response.Employee;
using Smart.Admin.Domain.Model.Request.HelpDocCatalog;
using Smart.Admin.Domain.Model.Response.HelpDocCatalog;

namespace Smart.Admin.Domain.Service
{
    /// <summary>
    /// 帮助文档服务
    /// </summary>
    public class HelpDocService: EmployeeExtensions
    {
        private readonly SmartAdminDbContext _context;
        private readonly ICacheService _redisService;
        private readonly IOptions<JwtOptions> _options;
        private readonly IMapper _mapper;
        public HelpDocService(SmartAdminDbContext context, ICacheService redisService, IOptions<JwtOptions> options, IMapper mapper)
        {
            _context = context;
            _redisService = redisService;
            _options = options;
            _mapper = mapper;
        }


        #region 文档目录
        /// <summary>
        /// 分页查询目录列表
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResponse<List<GetHelpDocCatalogResponse>>> GetHelpDocCatalogList(GetHelpDocCatalogListRequest request)
        {
            var response = new JsonResponse<List<GetHelpDocCatalogResponse>>();
            try
            {
                var query = from helpDocCatalog in _context.HelpDocCatalog
                            select new GetHelpDocCatalogResponse()
                            {
                                CreateTime = helpDocCatalog.CreateTime,
                                HelpDocCatalogId = helpDocCatalog.Id,
                                Sort = helpDocCatalog.Sort,
                                Name = helpDocCatalog.Name,
                                ParentId = helpDocCatalog.ParentId,
                                UpdateTime = helpDocCatalog.UpdateTime
                            };
                query = query.WhereIf(!string.IsNullOrEmpty(request.Name), p => p.Name.Contains(request.Name));
                query = query.Distinct();
                var data = await query.OrderBy(m => m.Sort).ToListAsync();


                response.code = "0";
                response.data = data;
                response.total = await query.CountAsync();
                return response;
            }
            catch (Exception ex)
            {
                return JsonResult.Error<List<GetHelpDocCatalogResponse>>(message: "系统错误");
            }
        }


        /// <summary>
        /// 创建文档目录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<JsonResponse> CreateHelpDocCatalog(CreateHelpDocCatalogRequest request)
        {
            try
            {
                if (request == null) return JsonResult.Error(message: "参数错误");
                var bl = await _context.HelpDocCatalog.AnyAsync(m => m.Name == request.Name && m.ParentId == request.ParentId);
                if (bl) return JsonResult.Error(message: "目录已存在");
                var model = _mapper.Map<HelpDocCatalogEntity>(request);
                model.CreateTime = DateTime.Now;
                model.UpdateTime = model.CreateTime;
                await _context.HelpDocCatalog.AddAsync(model);
                await _context.SaveChangesAsync();
                return JsonResult.Success();
            }
            catch (Exception ex)
            {
                return JsonResult.Error(message: "系统错误");
            }
        }


        /// <summary>
        /// 修改文档目录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<JsonResponse> UpdateHelpDocCatalog(UpdateHelpDocCatalogRequest request)
        {
            try
            {
                if (request == null) return JsonResult.Error(message: "参数错误");
                var model = await _context.HelpDocCatalog.FirstOrDefaultAsync(m => m.Id == request.HelpDocCatalogId);
                if (model == null) return JsonResult.Error(message: "数据不存在");
                var bl = await _context.HelpDocCatalog.AnyAsync(m => m.Name == request.Name && m.ParentId == request.ParentId && m.Id != request.HelpDocCatalogId);
                if (bl) return JsonResult.Error(message: "目录已存在");

                model.Sort = request.Sort;
                model.Name = request.Name;
                model.ParentId = request.ParentId;
                model.UpdateTime = DateTime.Now;

                _context.HelpDocCatalog.Update(model);
                await _context.SaveChangesAsync();
                return JsonResult.Success();
            }
            catch (Exception ex)
            {
                return JsonResult.Error(message: "系统错误");
            }
        }

        /// <summary>
        /// 删除文档目录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<JsonResponse> DeleteHelpDocCatalog(long helpDocCatalogId)
        {
            try
            {
                var model = await _context.HelpDocCatalog.AsNoTracking().FirstOrDefaultAsync(m => m.Id == helpDocCatalogId);
                if (model != null)
                {
                    var bl = await _context.HelpDoc.AsNoTracking().AnyAsync(m => m.CatalogId == helpDocCatalogId && m.IsDelete == false);
                    if (bl) return JsonResult.Error(message: "该目录下存在未删除的文档,删除失败");
                    _context.HelpDocCatalog.Remove(model);
                    await _context.SaveChangesAsync();
                }
                return JsonResult.Success();
            }
            catch (Exception ex)
            {
                return JsonResult.Error(message: "系统错误");
            }
        }

        #endregion

        #region 帮助文档
        /// <summary>
        /// 分页查询帮助文档列表
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResponse<List<GetHelpDocResponse>>> GetHelpDocPageList(GetHelpDocPageListRequest request)
        {
            var response = new JsonResponse<List<GetHelpDocResponse>>();
            try
            {
                var query = from helpDoc in _context.HelpDoc
                            join helpDocCatalog in _context.HelpDocCatalog on helpDoc.CatalogId equals helpDocCatalog.Id
                            where helpDoc.IsDelete == false
                            select new GetHelpDocResponse ()
                            {
                                Author=helpDoc.Author,
                                CatalogId=helpDoc.CatalogId,
                                CatalogName=helpDocCatalog.Name,
                                ContentHtml=helpDoc.ContentHtml,
                                ContentText=helpDoc.ContentText,
                                CreateTime=helpDoc.CreateTime,
                                HelpDocId = helpDoc.Id,
                                Sort=helpDoc.Sort,
                                Title=helpDoc.Title
                            };

                query = query.WhereIf(request.CatalogId.HasValue, p => p.CatalogId == request.CatalogId);

                query = query.WhereIf(request.StartCreateTime.HasValue, p => p.CreateTime >= request.StartCreateTime);
                query = query.WhereIf(request.EndCreateTime.HasValue, p => p.CreateTime <= request.EndCreateTime);

                query = query.WhereIf(!string.IsNullOrEmpty(request.Keyword), p => p.Title.Contains(request.Keyword) || p.Author.Contains(request.Keyword));
                var data = await query.OrderByDescending(m => m.Sort).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToListAsync();


                response.code = "0";
                response.data = data;
                response.total = await query.CountAsync();
                return response;
            }
            catch (Exception ex)
            {
                return JsonResult.Error<List<GetHelpDocResponse>>(message: "系统错误");
            }
        }


        /// <summary>
        /// 查询帮助文档信息
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResponse<GetHelpDocResponse>> GetHelpDocInfo(long helpDocId)
        {
            var response = new JsonResponse<GetHelpDocResponse>();
            try
            {
                var model = await _context.HelpDoc.AsNoTracking().Where(m=>m.IsDelete==false).FirstOrDefaultAsync(m=>m.Id == helpDocId);
                if(model == null) return JsonResult.Error<GetHelpDocResponse>(message: "数据不存在");
                response.code = "0";
                response.data = _mapper.Map<GetHelpDocResponse>(model);
                return response;
            }
            catch (Exception ex)
            {
                return JsonResult.Error<GetHelpDocResponse>(message: "系统错误");
            }
        }

        /// <summary>
        /// 创建帮助文档
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<JsonResponse> CreateHelpDoc(CreateHelpDocRequest request) 
        {
            try
            {
                if(request ==null) return JsonResult.Error(message: "参数错误");
                var bl = await _context.HelpDoc.AnyAsync(m => m.Title == request.Title);
                if (bl) return JsonResult.Error(message:"帮助文档标题已存在");
                var model = _mapper.Map<HelpDocEntity>(request);
                model.CreateTime = DateTime.Now;
                model.UpdateTime = model.CreateTime;
                await _context.HelpDoc.AddAsync(model);
                await _context.SaveChangesAsync();
                return JsonResult.Success();
            }
            catch (Exception ex)
            {
                return JsonResult.Error(message: "系统错误");
            }
        }


        /// <summary>
        /// 修改帮助文档
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<JsonResponse> UpdateHelpDoc(UpdateHelpDocRequest request)
        {
            try
            {
                if (request == null) return JsonResult.Error(message: "参数错误");
                var model = await _context.HelpDoc.Where(m=>m.IsDelete == false).FirstOrDefaultAsync(m => m.Id == request.HelpDocId);
                if (model == null) return JsonResult.Error(message:"数据不存在");
                var bl = await _context.HelpDoc.Where(m => m.IsDelete == false).AnyAsync(m => m.Title == request.Title && m.Id != request.HelpDocId);
                if (bl) return JsonResult.Error(message:"帮助文档标题已存在");

                model.Author=request.Author;
                model.ContentHtml=request.ContentHtml;
                model.ContentText=request.ContentText;
                model.CatalogId=request.CatalogId;
                model.Title=request.Title;
                model.UpdateTime = DateTime.Now;

                _context.HelpDoc.Update(model);
                await _context.SaveChangesAsync();
                return JsonResult.Success();
            }
            catch (Exception ex)
            {
                return JsonResult.Error(message: "系统错误");
            }
        }

        /// <summary>
        /// 删除帮助文档
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<JsonResponse> DeleteHelpDoc(DeleteHelpDocRequest request)
        {
            try
            {
                if(request == null || request.HelpDocIdList == null || request.HelpDocIdList.Count == 0) return JsonResult.Error(message: "参数错误");
                var list = await _context.HelpDoc.Where(m => request.HelpDocIdList.Contains(m.Id)).ToListAsync();
                if (list.Count > 0)
                {
                    foreach (var item in list)
                    {
                        item.IsDelete = true;
                    }
                    _context.HelpDoc.UpdateRange(list);
                    await _context.SaveChangesAsync();
                }
                return JsonResult.Success();
            }
            catch (Exception ex)
            {
                return JsonResult.Error(message: "系统错误");
            }
        }

        #endregion
    }
}
